#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
using namespace std;

bool GetQuery_string(string &query_string)
{
    std::string method = getenv("METHOD");
    std::string content_lenth;

    if (method == "POST")
    {
        int len = atoi(getenv("CONTENT_LENGTH"));
        char ch = 0;
        while (len)
        {
            int res = read(0, &ch, 1);
            if (res > 0)
            {
                len--;
                query_string.push_back(ch);
            }
        }
        return true;
    }
    else if (method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        return true;
    }
    else
    {
        return false;
    }
}

void CutSting(std::string &in, const std::string &sep, std::string &out1, std::string &out2)
{
    auto pos = in.find(sep);
    if (pos != std::string::npos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size());
    }
}

int main()
{
    std::string query_string;
    GetQuery_string(query_string);

    std::string str1;
    std::string str2;
    CutSting(query_string, "&", str1, str2);

    std::string name1;
    std::string value1;
    CutSting(str1, "=", name1, value1);

    std::string name2;
    std::string value2;
    CutSting(str2, "=", name2, value2);

    std::cout << name1 << ": " << value1 << std::endl;
    std::cout << name2 << ": " << value2 << std::endl;

    std::cerr << name1 << ": " << value1 << std::endl;
    std::cerr << name2 << ": " << value2 << std::endl;

    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());

    std::cout << "<html>";
    std::cout << "<head><meta charset=\"utf-8\"></head>";
    std::cout << "<body>";
    std::cout << "<h3>" << value1 << "+" << value2 << " = " << x + y << "</h3>";
    std::cout << "<h3>" << value1 << "-" << value2 << " = " << x - y << "</h3>";
    std::cout << "<h3>" << value1 << "*" << value2 << " = " << x * y << "</h3>";
    std::cout << "<h3>" << value1 << "/" << value2 << " = " << x / y << "</h3>";
    std::cout << "</body>";
    std::cout << "</html>";    
    return 0;
}